<template>
    <div class="container-message mb-60">
        <n-scrollbar x-scrollable>
            <ul class="user-list mt-20">
                <li class="avatar" v-for="(item, index) in currentOnlineUserList" :key="index">
                    <n-badge v-if="item.imageUrl === ''" :value="item.name === userName ? 0 : item.messageLen"
                        :max="99">
                        <n-avatar @click.stop="privatePersonUserMessage(item)" round :size="50" :style="{
                            color: 'yellow',
                            backgroundColor: '#18a058',
                        }">
                            {{ item.name.slice(0, 4) }}
                        </n-avatar>
                    </n-badge>
                    <n-badge v-else :value="item.name === userName ? 0 : item.messageLen" :max="99">
                        <n-avatar @click.stop="privatePersonUserMessage(item)" :src="item.imageUrl" round :size="50">
                        </n-avatar>
                    </n-badge>
                </li>
            </ul>
        </n-scrollbar>
        <common-comment ref="groupRef" v-model:user="userGroup" @update-user="handerSendGroup"
            @update-withdraw="handleUpdateWithdrawInfo" @withdraw-sendMessage="handleWithdrawSendMessage"
            :messageType="messageType"></common-comment>
        <n-drawer v-model:show="active" @after-leave="closePrivateUserMessage" width="100%" height="80%"
            :placement="'bottom'">
            <n-drawer-content>
                <template #header>
                    <n-flex justify="space-between">
                        <p style="flex:1;">正在和 {{ currentUser.name }} 聊天</p>
                        <n-popconfirm @positive-click="handleDeleteMessageHistory(currentUser.name)">
                            <template #trigger>
                                <n-button>删除记录</n-button>
                            </template>
                            一切都将一去杳然，任何人都无法将其恢复。
                        </n-popconfirm>
                    </n-flex>
                </template>
                <common-comment ref="commonRef" v-model:privateUser="privateUser"
                    @withdrawPrivate-Message="handleWithdrawPrivateSendMessage"
                    @update-privateUser="handerSendToPrivateUser" :messageType="messageType"></common-comment>
            </n-drawer-content>
        </n-drawer>
        <div class="mt-20" style="float: right;" @click="handleDeleteMessageHistory(currentUser.name)">1</div>
    </div>
</template>

<script setup lang="ts">
import bus from '@/utils/mitt';
import { groupMessage, personalMessage, privateChatHistory, groupChatHistory, deleteChatHistory, setCurrentMessageToRead, privateCloseWindow, revokeMessage } from '@/utils/socket';
import router from '@/router';
import { UserMessage } from './type';
// 消息撤回，已读，未读
const commonComment = defineAsyncComponent(() => import('../../components/comment/index.vue'));
const active = ref(false);
const loadingBar = useLoadingBar();
const message = useMessage();
const currentSocketId = ref('');
const userName = localStorage.getItem('u') as string;
const currentOnlineUserList = ref<any[]>([])
const userGroup = ref<UserMessage[]>([])
const groupRef: any = ref(null);
const privateUser = ref<UserMessage[]>([])
const commonRef: any = ref('');
const messageType = ref('group');
const currentUser = ref<any>('');
const isCheckCurrentView = ref(false);

function handerSendGroup(userData: UserMessage) {
    groupMessage(userData); // 父组件
    groupRef.value.groupScrollIntoView(userGroup.value);
}

function handerSendToPrivateUser(user: UserMessage) {
    user.name = currentUser.value.name;
    // 取出当前一对一用户进行窗口校验
    const currentOpentheWindowUser = currentOnlineUserList.value.filter((itemUser: any) => [user.name, userName].includes(itemUser.name));
    const whetherUpdateToRead: boolean = currentOpentheWindowUser.every(item => item.view);
    personalMessage({ ...user, sendUserName: userName }, currentSocketId.value);
    // 俩者都为打开窗口进行聊天时，设置当前消息为已读
    if (whetherUpdateToRead) {
        isCheckCurrentView.value = true;
        user.isRead = false;
        setCurrentMessageToRead({ sendUserName: userName, name: user.name, viewType: isCheckCurrentView.value }, currentSocketId.value);
        privateUser.value.push(user);
        commonRef.value.handerPrivate(privateUser.value);   // 消息滚动当前窗口最下面位置
        return;
    }
    privateUser.value.push(user);
    commonRef.value.handerPrivate(privateUser.value);

}

function handleDeleteMessageHistory(userName: string) {
    if (messageType.value === 'private') {
        deleteChatHistory(userName);
        privateUser.value = [];
        active.value = false;
        return;
    }
    deleteChatHistory('groupMessageList');
    userGroup.value = [];
}

function closePrivateUserMessage() {
    messageType.value = 'group';
    privateUser.value = [];
    isCheckCurrentView.value = false;
    // 关闭后将 view 设置为 false
    privateCloseWindow(userName);
}
// 群聊撤回消息
function handleWithdrawSendMessage(currentWithdrawMessage: UserMessage) {
    revokeMessage('groupMessageList', currentWithdrawMessage.id as string, 'group')
}

// 私聊撤回消息
function handleWithdrawPrivateSendMessage(currentWithdrawMessage: UserMessage) {
    revokeMessage({
        name: currentWithdrawMessage.name,
        sendName: userName,
        socketId: currentSocketId.value
    }, currentWithdrawMessage.id as string, 'private');
}

// 重新发送撤回消息其他逻辑处理
function handleUpdateWithdrawInfo(message: string) {
    console.info(message)
}

// 尝试重新连接
function init() {
    loadingBar.start();
    bus.on('current-gropUser', (socketUser: any) => {
        currentOnlineUserList.value = socketUser;
        groupChatHistory();
        loadingBar.finish();
    })
    // 群聊 
    bus.on('group-message', (messageData: any) => {
        userGroup.value.push(messageData);
        loadingBar.finish();
    })
    // 单聊
    bus.on('private-message', (messageData: any) => {
        countMessageLength(messageData.user)
        privateUser.value.push(messageData.user);
        loadingBar.finish();
        if (isCheckCurrentView.value) {
            setTimeout(() => {
                commonRef.value.handerPrivate(privateUser.value);
            }, 200)
        }

    })
    // 私聊历史记录
    bus.on('chat-history', (historyData: any) => {
        privateUser.value = historyData;
        loadingBar.finish();
    })
    // 群聊消息记录
    bus.on('group-chat-history', (historyData: any) => {
        userGroup.value = historyData;
        loadingBar.finish();
    })
    // 断开连接
    bus.on('disconnect-warning', () => {
        message.error('断开连接，请重试')
        loadingBar.finish();
    })
    //  实时处理： 已读未读 ｜ 群聊撤回消息 ｜ 单聊撤回消息
    bus.on('read-reolad-message', (type) => {
        if (type === 'reload') {
            console.info('read')
            // console.info(currentUser.value)
            privateChatHistory(userName);
            return;
        }

        if (type === 'groupReload') {
            groupChatHistory();
            return;
        }
        // 用户打开窗口实时变 没有打开窗口直接存数据
        if (userName) {
            privateChatHistory(userName);

        }
    })
}

// 打开私聊窗口
function privatePersonUserMessage(user: UserMessage) {
    if (userName === user.name) {
        message.warning('不能和自己吹牛B')
        return
    }
    // 设置自己的窗口
    currentOnlineUserList.value.forEach(item => {
        if (item.name === userName) {
            item.view = true;
        }
    })
    user.messageLen = 0;
    messageType.value = 'private';
    currentUser.value = user;
    currentSocketId.value = user.socketId;
    const currentOpentheWindowUser = currentOnlineUserList.value.filter((itemUser: any) => [user.name, userName].includes(itemUser.name));
    const whetherUpdateToRead: boolean = currentOpentheWindowUser.every(item => item.view);
    setCurrentMessageToRead({ sendUserName: userName, name: user.name, viewType: whetherUpdateToRead }, user.socketId);
    privateChatHistory(user.name); // 获取聊天历史记录
    message.success('选择和' + user.name + '吹牛B？');
    active.value = true;
}

// 消息统计
function countMessageLength(privateUserData: any) {
    currentOnlineUserList.value.forEach(item => {
        if (item.name === privateUserData.sendUserName) {
            item.messageLen = privateUserData.messageLen;
        }
    })
}



onMounted(() => {
    if (localStorage.getItem('t')) {
        init();
    } else {
        message.error('请先登录在嗨')
        router.push('/');
        loadingBar.finish();
    }

})
</script>

<style lang="scss" scoped>
.container-message {
    padding-left: 20px;
    padding-right: 20px;

    .user-content {
        display: flex;
    }

    .right-user-content {
        display: flex;
        justify-content: flex-end;
        position: relative;
    }



    .user-list {
        width: 400px;
        display: flex;

        li {
            margin-right: 10px;
            cursor: pointer;
        }
    }

    .message-view {
        width: 100%;

    }

    .message-input {
        width: calc(100%);
        height: 40px;
        border-radius: 10px;
        display: flex;
        background-color: #f2f3f5;

        input {
            flex: 1 auto;
            width: 80%;
            line-height: 40px;
            text-indent: 10px;
            font-size: 14px;
            outline: none;
            outline: 0;
            border: none;
            color: #8491a5;
            border-radius: 10px;
            background-color: #f2f3f5;
        }

        p {
            width: 30px;
            line-height: 40px;
        }
    }

    .message-content {
        color: #8491a5;
        font-size: 13px;
        padding: 8px;
        box-sizing: border-box;
        border-radius: 10px;
        background-color: #f2f3f5;
        position: relative;
    }

    .right-message-content {
        color: #8491a5;
        font-size: 14px;
        padding: 8px;
        box-sizing: border-box;
        border-radius: 10px;
        background-color: #feeadd;
        position: relative;
    }

    .time {
        color: #8491a5;
    }
}

.private-message {
    width: 100%;
}

.system-warning {
    width: 100%;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #8491a5;
    margin-top: 10px;
    margin-bottom: 10px
}
</style>